package com.example.sxt_practise.java并发编程;

import javax.swing.*;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * 模拟售票
 * @author gaofeng
 * date 2022年02月13日 9:43
 */
public class ExerciseSell {
    public static void main(String[] args) throws InterruptedException {
        Sell sell = new Sell(1000) ;

        List<Thread> threads = new ArrayList<>();
        List<Integer> amounts = new ArrayList<>() ;
        for (int i = 0; i < 2000; i++) {
            Thread thread = new Thread(() -> {
                Integer amount = sell.sell(random()) ;
                amounts.add(amount) ;
            }) ;
            thread.start();
            threads.add(thread) ;
        }

        for (Thread thread : threads) {
            thread.join();
        }
        // 卖票
        System.out.println("剩余的票数:{}" + sell.getAmount());
        // 买票
        //System.out.println("卖出的票数:{}" + amounts.stream().reduce(0, Integer::sum));
        Integer sum = 0 ;
        for (Integer amount : amounts) {
            System.out.println(amount);
            //sum += amount ;
        }
        System.out.println("卖出的票数:{}" + sum);
    }

    static SecureRandom random = new SecureRandom();
    public static Integer random() {
        return random.nextInt(5) + 1 ;
    }
}

class Sell {
    private Integer amount ;

    public Sell(Integer amount) {
        this.amount = amount;
    }

    public Integer getAmount() {
        return amount;
    }

    public Integer sell(Integer count) {
        if (this.amount >= count) {
            this.amount -= count ;
            return amount ;
        } else {
            return 0 ;
        }
    }
}
